#include"protocol.h"

int ConnectWork()
{
  int sockfd = socket(AF_INET,SOCK_STREAM,0);
  if(sockfd < 0)
  {
    perror("socket");
    return 1;

  }
  struct sockaddr_in server;
  server.sin_family = AF_INET;
  server.sin_addr.s_addr = inet_addr(PIP);
  server.sin_port = htons(PORT);
  if(connect(sockfd,(struct sockaddr*)&server,sizeof(server)) < 0)
  {
    perror("connect server");
    return 2;

  }
  return sockfd;

}
void ClienetWork(int sockfd,char* name)
{
    if(fcntl(0,F_SETFL,FNDELAY) < 0)//将标准输入设置为非阻塞状态
    {
      perror("fcntl");
      exit(1);

    }
    user uc;
    char buf[NAME+MSG] = {0};
    while(1)
    {
         strcpy(buf,name);
         ssize_t r_size = read(0,uc._msg,MSG);
         if(r_size >0)
         {
             uc._msg[r_size] = 0; 
             // fflush(stdout);
             strcpy(buf+NAME,uc._msg);
             send(sockfd,buf,NAME+MSG,0);//非阻塞方式发送                                 
         }
         memset(buf,0x00,MSG+NAME);
         ssize_t re_size = recv(sockfd,buf,NAME+MSG,MSG_DONTWAIT);
         if(re_size > 0)
         {
             strncpy(uc._name,buf,NAME);
             strncpy(uc._msg,buf+NAME,MSG);
             printf("%s:%s",uc._name,uc._msg);

         }

  }
  close(sockfd);

}


int main(int argc,char* argv[])
{
  if(argc != 2)
  {
    printf("Please into ./client [name]");
    exit(1);   

  }
  int sockfd = ConnectWork();
  ClienetWork(sockfd,argv[1]);
  return 0;

}
